﻿using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Practices.CompositeWeb;
using Microsoft.Practices.CompositeWeb.Utility;
using ModulesToolkit.DataAccess.Membership;
using ModulesToolkit.DataContracts.Membership;

namespace ModulesToolkit.Membership.Views
{
    public class GroupsListPresenter : Presenter<IGroupsListView>
    {
        #region Fields

        private readonly GroupsDtoRepository _groupsRepository;
        private readonly RolesRepository _rolesRepository;
        private readonly GroupRolesDtoRepository _groupRolesDtoRepository;
        private readonly MembersDtoRepository _groupMembersDtoRepository;
        private IEnumerable<GroupRoleDto> _groupRoles;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="GroupsListPresenter"/> class.
        /// </summary>
        /// <param name="groupsRepository">The groups repository.</param>
        /// <param name="rolesRepository">The roles repository.</param>
        /// <param name="groupRolesDtoRepository"></param>
        /// <param name="groupMembersDtoRepository">The group members dto repository.</param>
        public GroupsListPresenter(GroupsDtoRepository groupsRepository,
            RolesRepository rolesRepository,
            GroupRolesDtoRepository groupRolesDtoRepository,
            MembersDtoRepository groupMembersDtoRepository)
        {
            _groupsRepository = groupsRepository;
            _rolesRepository = rolesRepository;
            _groupRolesDtoRepository = groupRolesDtoRepository;
            _groupMembersDtoRepository = groupMembersDtoRepository;
        }

        #endregion Constructors

        #region Methods

        public void OnAddCommandClick()
        {
            this.View.GroupDto = new GroupDto();

            this.OnLoadMembersList();
            this.OnLoadRolesList();

            this.View.ShowDetailsPopup();
        }

        public void OnCancelCommandClick()
        {
            this.View.HideDetailsPopup();
        }

        public void OnSearchClick()
        {
            this.OnLoadGroupsList();
        }

        public override void OnViewInitialized()
        {
            // TODO: Implement code that will be executed the first time the view loads
        }

        public override void OnViewLoaded()
        {
            // TODO: Implement code that will be executed every time the view loads
        }

        public void OnEditCommand(int groupId)
        {
            this.View.EditingId = groupId;

            var group = this._groupsRepository.RetrieveGroups(new GroupDtoSearchCriteria { Id = groupId }).SingleOrDefault();
            Guard.ArgumentNotNull(group, "GroupId");
            this.View.GroupDto = group;
            //---------------------------------------------------------------------------------------
            var groupMembers = this._groupMembersDtoRepository.RetrieveGroupMembers(new GroupMemberDtoSearchCriteria { GroupId = groupId });
            this.View.FillGroupMembers(groupMembers);
            //----------------------------------------------------------------------------------------

            this.View.ShowDetailsPopup();

        }

        public void OnLoadGroupsList()
        {
            var entitySearchResult = this._groupsRepository.RetrieveGroups(this.View.SearchCriteria);
            this.View.FillGroupsList(entitySearchResult);
        }

        public void OnLoadMembersList()
        {
            var searhCriteria = this.View.MembersSearchCriteria;
            searhCriteria.SortField = "MemberName";
            var members = this._groupMembersDtoRepository.RetrieveMembers(searhCriteria);
            this.View.FillMembers(members);
        }

        public void OnLoadGroupMembersList()
        {
            var searchCroteria = this.View.GroupMembersSearchCriteria;
            searchCroteria.SortField = "MemberName";
            var groupMembers = this._groupMembersDtoRepository.RetrieveGroupMembers(searchCroteria);
            this.View.FillGroupMembers(groupMembers);
        }

        public void OnDeleteCommand(int id)
        {
            this._groupsRepository.DeleteGroup(id);
            this.OnLoadGroupsList();
        }

        public bool OnValidateGroupNameDublication(string name)
        {
            var result = _groupsRepository.RetrieveGroups(new GroupDtoSearchCriteria() { Name = name });
            return result.TotalRecords == 0;
        }

        public void OnOkCommandClicked()
        {
            if (this.View.IsValid)
            {
                if (this.View.EditingId == 0) // insert mode
                {
                    GroupDtoInsertIdentity group = this.View.GroupDto;
                    group.CreatedBy = Thread.CurrentPrincipal.Identity.Name;
                    group.CreationDate = DateTime.Now;

                    //group.Roles = GetCurrentRoles();

                    _groupsRepository.InsertGroup(group);
                }
                else
                {
                    var group = this.View.GroupDto;
                    group.LastUpdatedBy = Thread.CurrentPrincipal.Identity.Name;
                    group.LastUpdatedDate = DateTime.Now;

                    _groupsRepository.UpdateGroup(group);
                }

                this.View.HideDetailsPopup();
                this.OnLoadGroupsList();
            }
        }

        public void OnLoadRolesList()
        {
            // if no roles get all roles. 

            var roles = this._rolesRepository.GetRoles(this.View.RolesSearchCriteria);
            this.View.FillRolesList(roles);
        }
        public bool IsInGroup(int roleId)
        {
            return false;  //return this.GroupRoles.Any(grrl => grrl.RoleId == roleId);
        }
        #endregion Methods
    }
}